package com.darker.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.darker.reggie.common.BaseContext;
import com.darker.reggie.common.R;
import com.darker.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取路径
        String requestURI = request.getRequestURI();
        log.info("拦截到的请求:"+requestURI);
        //需要放行的路径
        String urls[] = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };


        //检查放行的路径
        boolean check = check(requestURI, urls);
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //如果登录了就放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户ID"+request.getSession().getAttribute("employee"));
            Long id= (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户ID"+request.getSession().getAttribute("user"));
            Long userid= (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userid);
            filterChain.doFilter(request, response);
            return;
        }
        //没有登录 回写数据表示没有登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("没有登录");
        return;

    }

    public boolean check(String requestURI, String urls[]) {
        for (String url : urls) {

            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
